<?php

namespace App\Http\Middleware;

use App\Model\Cart;
use App\Model\User;
use Closure;


class CheckUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {


        if (!$request->session()->has('user_info')) {

            $open_all = session("wechat.oauth_user.default")->toArray();
            $original = $open_all["original"];
            $user = new User;
            if (empty($res = $user->where('openid', '=', $original['openid'])->first())) {
                if (!$user->add_user($original))
                    return $this->error_url('/', '注册用户失败', 3);
            } else {
                if (!$res->update_user($original))
                    return $this->error_url('/', '更新用户失败', 3);
            }
            session(array("user_info" => $res->toArray()));

        }
        $user = session("user_info");
        if (empty($user))
            return $this->error_url('/', '登录失败', 3);

        if (!$request->session()->has('user.cart.num')) {
            $cart = new Cart();

            $where = array(
                array("where", "user_id", "=", $user["user_id"])
            );
            session(array("user.cart.num" => $cart->getSumByWhere($where)));
        }

        return $next($request);
    }

    private function error_url($url = '/', $message = '未知错误', $time = 3)
    {
        return view('errors.error', ['url' => $url, 'message' => $message, 'time' => $time]);
    }
}
